﻿using Sunny.UI;
using System.Collections.Generic;
using CoreShop.Model;
using CoreShop.Services;
using System;
using CoreShop.Model.UI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections;
using System.Security.Policy;
using SqlSugar.Extensions;
using Sunny.UI.Win32;
using System.Windows.Forms;
using System.ComponentModel;
using CoreShop.Library;
using System.Linq;
using NPOI.SS.Formula.Functions;
using System.Drawing;
using static CoreShop.Library.GlobalEnumVars;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Data;
using System.IO;
using MySqlX.XDevAPI.Relational;
using SqlSugar;
using NPOI.Util;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Runtime.InteropServices.ComTypes;
using CoreShop.Model.FromBody;
using static System.Windows.Forms.AxHost;
using NPOI.POIFS.Properties;
using Org.BouncyCastle.Asn1.Ocsp;
using CoreShop.App.Units.Interface;
using System.Threading.Tasks;
using Loading;
using static CoreShop.Model.FromBody.DataResultModel;
using System.Xml.Linq;

namespace CoreShop.App
{
    public partial class frmFoodSelect : UIForm
    {
        public int mPageIndex = 0;
        public bool returnValue;
        private long selectTypeId = 0;
        public List<corecmsfoodspec> foodlstSource = new List<corecmsfoodspec>();
        public corecmsfoodcategory foodcategory = null;
        public corecmsfoodspec specModel = new corecmsfoodspec();
        public List<corecmsfoodspec> specList = new List<corecmsfoodspec>();
        OpaqueCommand cmd1 = new OpaqueCommand();
        public string number = "";
        private long foodTypeId = 0;
        public int stand = 0;
        private long excludeScaleId = 0;

        private bool isFocusInput = false;
        public static System.Timers.Timer timer_focus = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_foodspecs"></param>
        /// <param name="SelectMultiFlag"></param>
        /// <param name="_stand"></param>
        /// <param name="_excludeScaleId">排除的称ID</param>
        public frmFoodSelect(List<corecmsfoodspec> _foodspecs,bool SelectMultiFlag = false,int _stand = 0,long _excludeScaleId = 0)
        {
            InitializeComponent();
            foodlstSource = _foodspecs;
            stand = _stand;
            excludeScaleId = _excludeScaleId;
            if (timer_focus == null)
            {
                timer_focus = new System.Timers.Timer();
                timer_focus.Interval = 200;
                timer_focus.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
                timer_focus.Enabled = false;
            }
            dgvFoodList.MultiSelect = SelectMultiFlag;
            if (SelectMultiFlag)
            {
                lblMessage.Text = "点击表头的<选择>执行【全选】或【全取消】";
                dgvFoodList.Columns["isSelected"].Visible = true;
            }
            if (stand > 0)
                dgvFoodList.Columns["weighPlu"].Visible = true;
            //this.ShowFullScreen = AppConstVars.showFullScreen;
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (!isFocusInput)
                {
                    this.txtSearch.Invoke(new Action(() =>
                    {
                        this.txtSearch.Focus();
                    }));
                }
            }
            catch { }
        }


        private void Food_Load(object sender, System.EventArgs e)
        {
            mPageIndex = 1;
            LoadFoodCategroy();
            if ((foodlstSource == null) || (foodlstSource.Count == 0))
            {
                LoadDataList(0, number);
            } else
            {
                this.dgvFoodList.AutoGenerateColumns = false;
                this.binDetail.DataSource = foodlstSource;
                this.dgvFoodList.DataSource = this.binDetail;
            }
            if (timer_focus != null) timer_focus.Enabled = true;
        }


        #region 加载信息列表

        private Expressionable<corecmsfoodspec, corecmsfood> GetExpressionable(string sName)
        {
            var where = Expressionable.Create<corecmsfoodspec, corecmsfood>();
            where = where.And((f, s) => s.isDelete == false && s.sellStatus != 0 && f.onLine == true);

            if (stand > 0)
                where = where.And((f, s) => f.weighType == (int)Library.GlobalEnumVars.WeighType.Weigh && s.stand > (int)Library.GlobalEnumVars.stand.Stand);

            if (foodTypeId > 0)
            {
                List<long> typeIds = new List<long>();
                if (foodTypeId <= AppConstVars.sysStore.corpId)
                {
                    typeIds = new corecmsfoodcategoryServices().AsQueryable()
                    .Where(p => p.tenantId == foodTypeId).Select(p => p.id).ToList();
                }
                else
                {
                    typeIds = new corecmsfoodcategoryServices().GetChildrenIds(foodTypeId);
                }

                if (typeIds.Count > 0)
                    where = where.And((f, s) => s.foodTypeId == foodTypeId || typeIds.Contains(s.foodTypeId));
                else
                    where = where.And((f, s) => s.foodTypeId == foodTypeId);
            }

            if (excludeScaleId > 0)
            {
                List<long> foodSpecIds = new corecmsscaledetailServices().AsQueryable().Where(p => p.scaleId == excludeScaleId).Select(p => p.foodSpecId).ToList();
                if (foodSpecIds.Count > 0) where = where.And((f, s) => !foodSpecIds.Contains(f.id));
            }

            if (!string.IsNullOrEmpty(sName))
                where = where.And((f, s) => f.name.Contains(sName) || f.number.Contains(sName) || f.code.Contains(sName)
                || s.byName.Contains(sName) || s.helpCode.Contains(sName) || s.pinYin.Contains(sName));
            return where;
        }

        private void LoadDataList(Int64 sTypeID, string str)
        {
            foodTypeId = sTypeID;
            var count = 0;
            btnPg.PageSize = 200;
            foodlstSource = new corecmsfoodspecServices().QueryPageSpecAsync(ref count, mPageIndex, btnPg.PageSize, GetExpressionable(str));
            if (excludeScaleId > 0)
               foodlstSource = foodlstSource.OrderBy(p=>p.weighPlu).ToList();
            this.dgvFoodList.AutoGenerateColumns = false;
            this.binDetail.DataSource = foodlstSource;
            this.dgvFoodList.DataSource = this.binDetail;
            btnPg.TotalCount = count;
            lblTotal.Text = $"共{count}条,{btnPg.PageSize}条/每页";
            btnSave.Enabled = false;
        }

        
        private void LoadFoodCategroy()
        {
            new FoodUtil().LoadFoodCategroy(tvFood);            
            if ((foodlstSource == null) || (foodlstSource.Count == 0))
                LoadDataList(0, "");
        }
        
        #endregion

        private void btnSerach_Click(object sender, EventArgs e)
        {
            LoadDataList(0, txtSearch.Text.Trim());
        }

        private void ubtn_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tvFood_AfterSelect(object sender, TreeViewEventArgs e)
        {
            selectTypeId = CommFunc.ConvertToInt64(e.Node.Tag);
            foodcategory = new corecmsfoodcategoryServices().GetById(selectTypeId);
            LoadDataList(selectTypeId, "");
        }
        

        private void btnSave_Click(object sender, EventArgs e)
        {
        }


        private void txtSearch_OkButtonClick(object sender, string value)
        {
            btnSerach_Click(null, null);
        }

        private void btnAddInfo_Click(object sender, EventArgs e)
        {
            var foodModel = new corecmsfood();
            foodModel.foodTypeId = selectTypeId;
            SetFoodInfo(foodModel);
        }

        private void SetFoodInfo(corecmsfood foodInfo)
        {            
            //frmFoodInfo frm = new frmFoodInfo(foodInfo.id, foodInfo.foodTypeId);
            //frm.ShowDialog();
            //LoadDataList(selectTypeId, txtSearch.Text.Trim());
            //frm.Dispose();
        }

        private void txtSearch_Enter(object sender, EventArgs e)
        {
            isFocusInput = true;
        }

        private void txtSearch_Leave(object sender, EventArgs e)
        {
            isFocusInput = false;
        }

        private void frmFoodSelect_Shown(object sender, EventArgs e)
        {
            txtSearch.Focus();
        }

        private void setSelectRow() 
        {
            if (dgvFoodList.MultiSelect)
            {
                List<corecmsfoodspec> detailsList = this.binDetail.DataSource as List<corecmsfoodspec>;
                specList = detailsList.Where(p => p.isSelected == 1).ToList();
                if ((specList != null) && (specList.Count > 0))
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                else
                    ShowInfoTip("没有选择数据!");
            }
            else
            {
                if (dgvFoodList.CurrentRow != null)
                {
                    long foodspedId = CommFunc.ConvertToInt64(dgvFoodList.CurrentRow.Cells["id"].Value);
                    specModel = foodlstSource.Where(x => x.id == foodspedId).FirstOrDefault();
                    if (specModel != null)
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    else
                        ShowInfoTip("没有选择数据!");
                }
            }
        }

        private void frmFoodSelect_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if ((string.IsNullOrEmpty(txtSearch.Text)) || (foodlstSource.Count == 1))
                    {
                        setSelectRow();
                    }
                    else {
                        btnSerach_Click(null,null);
                    }
                    break;
                case Keys.Up:
                    this.binDetail.MovePrevious();
                    break;
                case Keys.Down:
                    this.binDetail.MoveNext();
                    break;

            }
        }

        private void dgvFoodList_DoubleClick(object sender, EventArgs e)
        {
            if (!dgvFoodList.MultiSelect) setSelectRow();
        }

        private void btnAddGoods_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.addproduct, 0)) return;
            frmFoodInfo frm = new frmFoodInfo(0, selectTypeId, "");
            if (frm.ShowDialog() == DialogResult.OK)
            {
                LoadDataList(selectTypeId, txtSearch.Text.Trim());
            }
            if (frm.isNewCategory)
            {
                btnRefresh_Click(null, null);
            }
        }

        private async void btnDownGoods_ClickAsync(object sender, EventArgs e)
        {
            cmd1.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                var exchange = new corecmsexchangeServices().GetDataById(AppConstVars.sysUser.storeId);
                string msg = "";
                List<corecmsfood> foodList = new List<corecmsfood>();
                var remoteService = new PosRemoteServices(AppConstVars.sysUser.ccessToken);
                var goodsResult = await FoodApiUtil.GetGoodDataList(AppConstVars.sysStore, AppConstVars.sysUser, exchange);

                remoteService.GetGoodCategoryList(AppConstVars.sysStore, AppConstVars.sysUser, exchange, ref msg);
                msg = string.Format("同步的商品数据为<{0}>条记录。<{1}>", goodsResult.count, goodsResult.msg);
                UIMessageBox.Show(msg);
            }
            catch (Exception)
            {
            }
            finally { cmd1.HideOpaqueLayer(); }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            setSelectRow();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadFoodCategroy();
            LoadDataList(0, number);
        }

        private void dgvFoodList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvFoodList.MultiSelect)
            {
                int rowId = e.RowIndex;
                int colId = e.ColumnIndex;
                if ((rowId < 0) || (colId < 0)) return;
                int value = CommFunc.ConvertToInt32(dgvFoodList.Rows[rowId].Cells[1].Value) == 0 ? 1 : 0;
                dgvFoodList.Rows[rowId].Cells[1].Value = value;
            }
        }

        private void dgvFoodList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvFoodList.MultiSelect)
            {
                if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
                {
                    DataGridViewRow row = dgvFoodList.Rows[e.RowIndex];
                    if (CommFunc.ConvertToInt32(dgvFoodList.Rows[e.RowIndex].Cells[1].Value) == 1)
                    {
                        e.CellStyle.BackColor = Color.Moccasin;
                        e.CellStyle.ForeColor = Color.Black;
                    }
                    else
                    {
                        // 设置未选中行的样式
                        e.CellStyle.BackColor = Color.White;
                        e.CellStyle.ForeColor = Color.Black;
                    }
                }
            }            
        }

        private void btnPg3_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            mPageIndex = pageIndex;
            LoadDataList(0, txtSearch.Text.Trim());
        }

        private void dgvFoodList_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dgvFoodList.Rows.Count == 0) return;
            if (dgvFoodList.Columns[e.ColumnIndex].Name.ToString() == "isSelected")
            {
                var value = CommFunc.ConvertToInt32(dgvFoodList.Rows[0].Cells[e.ColumnIndex].Value);
                value = value == 0 ? 1:0;
                for (int i = 0; i < dgvFoodList.Rows.Count; i++)
                {
                    dgvFoodList.Rows[i].Cells[1].Value = value;
                }
            }
        }
    }
}